// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', [
    'ionic',
    'ngCordova',
    // main modules-----------------------controller
    // welcome
    // home
    'start.home.ctrl',
    // makefriend
    'start.makefriend.ctrl',
    // user
    'start.user.ctrl',
    'start.user.useredit.ctrl',
    'start.user.money.ctrl',
    'start.user.money.addmoney.ctrl',
    'start.user.money.getmoney.ctrl',
    'start.user.orderway.ctrl',
    'start.user.orderguide.ctrl',
    'start.user.ordervisitor.ctrl',
    'start.user.orderdetailvisitor.ctrl',
    'start.user.orderdetailguide.ctrl',
    'start.user.orderpay.ctrl',
    'start.user.ordercomplaint.ctrl',
    'start.user.ordercomment.ctrl',
    'start.user.auth.authselect.ctrl',
    'start.user.auth.authguide.ctrl',
    'start.user.auth.authrealname.ctrl',
    'start.user.friend.attentionlist.ctrl',
    'start.user.friend.fanslist.ctrl',
    // guide
    'start.guide.ctrl',
    'start.guide.guidedetail.ctrl',
    'start.guide.guideorder.ctrl',
    'start.guide.guideevaluate.ctrl',
    'start.guide.guideevaluatelist.ctrl',
    // common
    'start.common.welcome.ctrl',
    'start.common.login.ctrl',
    'start.common.register.ctrl',
    'start.common.registerthirdpart.ctrl',
    'start.common.password.ctrl',
    'start.common.article.ctrl',
    'start.common.message.ctrl',
    'start.common.messagelist.ctrl',
    'start.common.setting.ctrl',
    'start.common.feedback.ctrl',
    'start.common.iframe.ctrl',
    'start.common.cityselect.ctrl',
    // main modules-----------------------services
    'starter.services',
    'starter.common.service',
    'starter.user.service',
    'starter.home.service',
    'starter.auth.service',
    'starter.guide.service',

    'ion-datetime-picker',
    'ionic-citypicker',
    'ion-gallery'
  ])
  .config(function($stateProvider, $httpProvider, ionGalleryConfigProvider, $urlRouterProvider, $ionicConfigProvider) {

    // 配置$http请求
    // 以表单形式 提交数据
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
    $httpProvider.defaults.transformRequest = function(data) {
      if (data === undefined) return data;
      return $.param(data);
    };

    // 就能禁止侧边滑动返回。
    $ionicConfigProvider.views.swipeBackEnabled(false);

    ionGalleryConfigProvider.setGalleryConfig({
      action_label: '关闭',
      toggle: false,
      row_size: 1,
      fixed_row_size: true
    });

    //设置设备样式
    $ionicConfigProvider.platform.ios.tabs.style('standard');
    $ionicConfigProvider.platform.ios.tabs.position('bottom');
    $ionicConfigProvider.platform.android.tabs.style('standard');
    $ionicConfigProvider.platform.android.tabs.position('standard');

    //center:标题居中，left:标题居左，right:标题居右
    $ionicConfigProvider.platform.ios.navBar.alignTitle('center');
    $ionicConfigProvider.platform.android.navBar.alignTitle('center');

    //设置返回按钮属性
    $ionicConfigProvider.platform.ios.backButton.previousTitleText('').icon('ion-ios-arrow-thin-left');
    $ionicConfigProvider.platform.android.backButton.previousTitleText('').icon('ion-android-arrow-back');

    //设置设备控件
    $ionicConfigProvider.platform.ios.views.transition('ios');
    $ionicConfigProvider.platform.android.views.transition('android');

    // Ionic uses AngularUI Router which uses the concept of states
    // Learn more here: https://github.com/angular-ui/ui-router
    // Set up the various states which the app can be in.
    // Each state's controller can be found in controllers.js
    $stateProvider

      .state('welcome', {
        url: '/welcome',
        cache: false,
        templateUrl: 'app/common/welcome/welcome.html',
        controller: 'WelcomeCtrl'
      })

      // setup an abstract state for the tabs directive
      .state('tab', {
        url: '/tab',
        abstract: true,
        templateUrl: 'app/tabs.html'
      })

      // Each tab has its own nav history stack:

      .state('tab.home', {
        url: '/home',
        cache: true,
        views: {
          'tab-home': {
            templateUrl: 'app/home/home.html',
            controller: 'HomeCtrl'
          }
        }
      })
      /**
       * ************************************************************************************************
       * guide
       * ************************************************************************************************
       */
      .state('tab.guide', {
        url: '/guide/:serviceKinds',
        views: {
          'tab-guide': {
            templateUrl: 'app/guide/guide.html',
            controller: 'GuideCtrl'
          }
        }
      })
      .state('guidedetail', {
        url: '/guidedetail/:guideId',
        cache: false,
        templateUrl: 'app/guide/guidedetail/guidedetail.html',
        controller: 'guidedetailCtrl'
      })
      .state('guideorder', {
        url: '/guideorder/:guideId',
        cache: false,
        templateUrl: 'app/guide/guideorder/guideorder.html',
        controller: 'guideorderCtrl'
      })
      .state('guideevaluate', {
        url: '/guideevaluate/:orderId',
        cache: false,
        templateUrl: 'app/guide/guideevaluate/guideevaluate.html',
        controller: 'guideevaluateCtrl'
      })
      .state('guideevaluatelist', {
        url: '/guideevaluatelist/:guideId',
        cache: false,
        templateUrl: 'app/guide/guideevaluatelist/guideevaluatelist.html',
        controller: 'guideevaluatelistCtrl'
      })
      /**
       * ************************************************************************************************
       * makefriend
       * ************************************************************************************************
       */
      .state('tab.makefriend', {
        url: '/makefriend',
        views: {
          'tab-makefriend': {
            templateUrl: 'app/makefriend/makefriend.html',
            controller: 'MakefriendCtrl'
          }
        }
      })
      /**
       * ************************************************************************************************
       * user
       * ************************************************************************************************
       */
      .state('tab.user', {
        url: '/user',
        views: {
          'tab-user': {
            templateUrl: 'app/user/user.html',
            controller: 'UserCtrl'
          }
        }
      })
      .state('useredit', {
        url: '/useredit',
        cache: false,
        templateUrl: 'app/user/userEdit/userEdit.html',
        controller: 'UserEditCtrl'
      })
      .state('money', {
        url: '/money',
        cache: false,
        templateUrl: 'app/user/money/money.html',
        controller: 'MoneyCtrl'
      })
      .state('addmoney', {
        url: '/addmoney',
        cache: false,
        templateUrl: 'app/user/money/addmoney/addmoney.html',
        controller: 'addmoneyCtrl'
      })
      .state('getmoney', {
        url: '/getmoney',
        cache: false,
        templateUrl: 'app/user/money/getmoney/getmoney.html',
        controller: 'getmoneyCtrl'
      })
      .state('orderway', {
        url: '/orderway',
        cache: false,
        templateUrl: 'app/user/order/orderway.html',
        controller: 'orderwayCtrl'
      })
      .state('ordervisitor', {
        url: '/ordervisitor',
        cache: false,
        templateUrl: 'app/user/order/ordervisitor.html',
        controller: 'ordervisitorCtrl'
      })
      .state('orderguide', {
        url: '/orderguide',
        cache: false,
        templateUrl: 'app/user/order/orderguide.html',
        controller: 'orderguideCtrl'
      })
      .state('orderdetailvisitor', {
        url: '/orderdetailvisitor/:orderId',
        cache: false,
        templateUrl: 'app/user/order/orderdetailvisitor.html',
        controller: 'orderdetailvisitorCtrl'
      })
      .state('orderdetailguide', {
        url: '/orderdetailguide/:orderId',
        cache: false,
        templateUrl: 'app/user/order/orderdetailguide.html',
        controller: 'orderdetailguideCtrl'
      })
      .state('orderpay', {
        url: '/orderpay/:orderId',
        cache: false,
        templateUrl: 'app/user/order/orderpay.html',
        controller: 'orderpayCtrl'
      })
      .state('ordercomplaint', {
        url: '/ordercomplaint/:orderId',
        cache: false,
        templateUrl: 'app/user/order/ordercomplaint.html',
        controller: 'ordercomplaintCtrl'
      })
      .state('ordercomment', {
        url: '/ordercomment/:orderId',
        cache: false,
        templateUrl: 'app/user/order/ordercomment.html',
        controller: 'ordercommentCtrl'
      })
      .state('authselect', {
        url: '/authselect',
        cache: false,
        templateUrl: 'app/user/auth/authselect.html',
        controller: 'authselectCtrl'
      })
      .state('authguide', {
        url: '/authguide',
        cache: false,
        templateUrl: 'app/user/auth/authguide.html',
        controller: 'authguideCtrl'
      })
      .state('authrealname', {
        url: '/authrealname',
        cache: false,
        templateUrl: 'app/user/auth/authrealname.html',
        controller: 'authrealnameCtrl'
      })
      .state('attentionlist', {
        url: '/attentionlist',
        cache: false,
        templateUrl: 'app/user/friend/attentionList.html',
        controller: 'friendattentionlistCtrl'
      })
      .state('fanslist', {
        url: '/fanslist',
        cache: false,
        templateUrl: 'app/user/friend/fansList.html',
        controller: 'friendfanslistCtrl'
      })
      /**
       * ************************************************************************************************
       * common
       * ************************************************************************************************
       */
      .state('login', {
        url: '/login',
        templateUrl: 'app/common/login/login.html',
        controller: 'LoginCtrl'
      })
      .state('register', {
        url: '/register',
        templateUrl: 'app/common/register/register.html',
        controller: 'RegisterCtrl'
      })
      .state('registerthirdpart', {
        url: '/registerthirdpart',
        templateUrl: 'app/common/registerthirdpart/registerthirdpart.html',
        controller: 'registerthirdpartCtrl'
      })
      .state('password', {
        url: '/password',
        templateUrl: 'app/common/password/password.html',
        controller: 'PasswordCtrl'
      })
      .state('article', {
        url: '/article/:articleId',
        templateUrl: 'app/common/article/article.html',
        controller: 'ArticleCtrl'
      })
      .state('messagelist', {
        url: '/messagelist',
        templateUrl: 'app/common/message/messageList.html',
        controller: 'MessageListCtrl',
        cache: false,
      })
      .state('message', {
        url: '/message/:messageId',
        templateUrl: 'app/common/message/message.html',
        controller: 'MessageCtrl',
        cache: false,
      })
      .state('cityselect', {
        url: '/cityselect',
        templateUrl: 'app/common/citySelect/citySelect.html',
        controller: 'CitySelectCtrl'
      })
      .state('setting', {
        url: '/setting',
        templateUrl: 'app/common/setting/setting.html',
        controller: 'SettingCtrl'
      })
      .state('iframe', {
        url: '/iframe/:type/:name/:url',
        templateUrl: 'app/common/iframe/iframe.html',
        cache: false,
        controller: 'iframeCtrl'
      })
      .state('feedback', {
        url: '/feedback',
        templateUrl: 'app/common/feedback/feedback.html',
        controller: 'FeedbackCtrl'
      });


    var appstateopenAppTimes = JSON.parse(window.localStorage.getItem("appstate")) || {
      openAppTimes: 0,
    };
    // 如果是第一次进入app 先进入欢迎页
    $urlRouterProvider.otherwise(appstateopenAppTimes.openAppTimes == 0 ? '/welcome' : '/tab/home');

    // 如果是第一次进入app 先进入欢迎页
    // $urlRouterProvider.otherwise( '/welcome' );


  })


  .run(function($ionicPlatform, $$CommonService, $$CityService, $$AuthService, $ionicLoading, $$GeocoderService, $rootScope, $timeout, $$AppUpdateService, $location, $$LocalStorage, $ionicPopup, $state, $$UserDataService, $ionicHistory) {

    // 图片预加载
    // 登录页背景图
    new Image().src = "img/denglu-bg@3x_compressed.jpg";

    // app 配置
    $rootScope.config = {
      version: "1.1.2",
      serverHost: "https://www.appserver.com/",
      // serverHost: "https://localhost:9999/",
      imageUploadUrl: "https://www.appserver.com/pic/",
      // apiHost: "https://192.168.1.23:9999/",
      apiHost: "https://www.appserver.com/",
      // apiHost: "https://localhost:9999/test/",
      // 接口签名秘钥
      secretkey: '',
      secretkey_Android: "S8KcilmwXQ4NHMmMwvwydB6gBOUMOhe5rRnR",
      secretkey_IOS: "bvQeJOzOddYiqHdF7hbWt7Xb2tdPWGqMZA5r",
      isLogined: false,
      // 是否显示第三方登录
      isShowThreePartLogin: false,
      // 是否显示第三方分享
      isShowThreePartShare: false,
      // 是否微信浏览器
      isWeixin: window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == 'micromessenger',
      // 是否安装微信app
      isInstallWeixinApp: false,
      // 是否是cordova应用
      isWebView: ionic.Platform.isWebView(),
      // 是否是苹果手机或浏览器
      isIOS: ionic.Platform.isIOS(),
      isAndroid: ionic.Platform.isAndroid(),
      // appWidth: screen.width,
      // appHeight: screen.height,
      appWidth: document.body.scrollWidth,
      appHeight: document.body.scrollHeight,
      // 微信appID
      wxappId: "",
      // 登录成功后自动返回的页面
      backPath: "",
      // 未登录要求返回的页面
      backPathNologin: "",
      city: {
        id: 369,
        key: "K",
        name: "昆明市",
        detailname: "",
        set: false
      },
      thirdpartLogin: {
        way: null, // "qq" "wechat" "weibo",
        openid: "",
      }
    };
    $rootScope.config.secretkey = $rootScope.config.isIOS ? $rootScope.config.secretkey_IOS : $rootScope.config.secretkey_Android;
    console.log($rootScope.config);

    // app 状态变量
    $rootScope.appstate = $$LocalStorage.getObj("appstate");
    if ($rootScope.appstate == null) {
      $rootScope.appstate = {
        openAppTimes: 0,
        firstOpenTime: new Date().getTime(),
        lastOpenTime: new Date().getTime(),
        geolocation: {
          address: "",
          lat: 0,
          lng: 0
        },
        suitableVsersion: {
          appUrl: "https://www.appserver.com/apk/android-release-1.1.2_112_jiagu_sign.apk",
          content: "",
          device: ($rootScope.config.isIOS ? 2 : 1),
          isForce: 0,
          versionId: $rootScope.config.version,
        }
      };
    }
    $rootScope.appstate.openAppTimes++;
    $rootScope.appstate.lastOpenTime = new Date().getTime();
    $$LocalStorage.setObj("appstate", $rootScope.appstate);

    console.log($rootScope.appstate);


    $rootScope.makeuseranth = function() {
      if ($rootScope.isLogined()) {
        $location.path("authselect");
      } else {
        $location.path("login");
      }
    };

    $rootScope.toiframepage = function(item) {
      console.log(item);
      if (item.type == 1) {
        $location.path(item.link);
      } else if (item.type == 2 || item.type == 3) {
        // console.log("iframe/" + encodeURIComponent(item.link));
        $location.path("iframe/" + encodeURIComponent(item.type) + "/" + encodeURIComponent(item.name) + "/" + encodeURIComponent(item.link));
      }
    };


    // 获取本地登录信息
    $rootScope.userData = $$UserDataService.getCacheUserData();
    console.log($rootScope.userData);

    // 查看是否登录
    $rootScope.isLogined = function() {
      if ($rootScope.userData.token == null || $rootScope.userData.token == undefined || $rootScope.userData.token == "") {
        console.log("isLogined()-- 未登录");
        $rootScope.config.isLogined = false;
        return false;
      } else {
        console.log("isLogined()-- 已登录");
        $rootScope.config.isLogined = true;
        // 检查token过期
        return true;
      }
    };
    $rootScope.isLogined();

    // 根据详细地址 找到城市数据中的城市
    $rootScope.changeAppCityByDetailCityName = function(detailname) {
      $$CityService.getallcitys()
        .then(function(res) {
          for (var i in res.data) {
            if (detailname.indexOf(res.data[i].city) != -1) {
              if ($rootScope.config.city.name != res.data[i].city) {
                $rootScope.config.city.id = res.data[i].city;
                $rootScope.config.city.name = res.data[i].city;
                break;
              } else {
                break;
              }
            }
          }
        });
    };


    // 打开app 获取定位信息
    // 更新用户坐标定位更新
    $$GeocoderService.getlatLng()
      .then(function(res) {
        console.log(res);
        // alert(JSON.stringify(res));
        $rootScope.appstate.geolocation.lng = res.lng;
        $rootScope.appstate.geolocation.lat = res.lat;
        // 根据坐标获取城市详细信息
        $$GeocoderService.getCityBylnglat($rootScope.appstate.geolocation)
          .then(function(res) {
            $rootScope.config.city.detailname = res.detail.detail;
            $rootScope.changeAppCityByDetailCityName($rootScope.config.city.detailname);
          });
        $$LocalStorage.setObj("appstate", $rootScope.appstate);
        // 登录过 提交坐标数据
        if ($rootScope.config.isLogined) {
          // 提交坐标更新
          $$AuthService.usergeoLocation($rootScope.appstate.geolocation)
            .then(function(res) {
              // alert(JSON.stringify(res));
            }, function(err) {
              // alert(JSON.stringify(err));
              $ionicLoading.hide();
            });
        }
      }, function(err) {
        // alert("定位失败",JSON.stringify(err));
      });

    // 获取服务分类
    $rootScope.hotCatalogData = [];
    $$CommonService.hotCatalog()
      .then(function(res) {
        $rootScope.hotCatalogData = res.data.list;
      });

    ////////////////
    // 获取本地缓存用户数据 //
    // 如果没有缓存用户信息，赋默认对象
    ////////////////


    // 需要登录操作才可以进行操作
    // backPath 登录成功后跳回登录之前的页面
    $rootScope.needLogin = function(backPath) {
      // return true;
      if ($rootScope.isLogined() == false) {
        $rootScope.config.backPath = backPath || "";
        $ionicLoading.show({
          template: "请登录",
          noBackdrop: true,
          duration: 1500
        });
        $location.path("login");
        return false;
      } else {
        return true;
      }
    };

    // 请重新登录
    $rootScope.needReLogin = function(backPath) {
      $$LocalStorage.remove("userData");
      $rootScope.userData = $$UserDataService.getCacheUserData();
      // 如果是app端
      if ($rootScope.config.isWebView) {
        // 设计极光推送别名为nologin
        // $$JPushService.setAlias("nologin");
      }
      $ionicLoading.show({
        template: "请重新登录",
        noBackdrop: true
      });
      $timeout(function() {
        $rootScope.config.backPath = backPath || "";
        $location.path("login");
        $ionicLoading.hide();
      }, 1000);
    };

    // 需要登录操作才可以进行操作
    // backPath 登录成功后跳回登录之前的页面
    $rootScope.goBackPage = function(pageName) {
      // 如果设置前置跳转页面
      if (pageName != undefined && pageName != "" && pageName != null) {
        $location.path(pageName);
      } else {
        // 如果没有历史记录 回到首页
        if ($ionicHistory.viewHistory().backView == null) {
          $location.path("tab/home");
          window.location.reload();
        } else {
          $rootScope.$ionicGoBack();
        }
      }
    };

    // 封装 alertPopup 方法
    $rootScope.alertPopup = function(title) {
      $ionicPopup.alert({
        title: title,
        okText: '确定', // String (默认: 'OK')。OK按钮的文字。
        okType: 'button-calm', // String (默认: 'button-positive')。OK按钮的类型。
      }).then(function(res) {
        console.log('确认提示框');
      });
    };


    // 路由监听事件
    // 调整到一级目录菜单 顶部导航背景色为白色 子菜单为蓝色
    $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
      // console.log('stateChangeStart',toState);
      if (toState.name == "tab.home" || toState.name == "tab.applystudy" || toState.name == "tab.onlinestudy" || toState.name == "tab.offlinestudy" || toState.name == "tab.user") { //如果是首页 header变成白色主题
        $(".cc_bar_head_blue").removeClass('cc_bar_head_blue').addClass("cc_bar_head_white");
      } else {
        $(".cc_bar_head_white").removeClass('cc_bar_head_white').addClass("cc_bar_head_blue");
      }
    });
    // stateChangeSuccess 当模板解析完成后触发
    $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
      // console.log('stateChangeSuccess',toState);
    });
    // $stateChangeError 当模板解析过程中发生错误时触发
    $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error) {
      // console.log('stateChangeError',toState);
    });


    $ionicPlatform.ready(function() {
      if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(false);
        cordova.plugins.Keyboard.disableScroll(true);
      }
      if (window.StatusBar) {
        StatusBar.styleDefault();
        StatusBar.overlaysWebView(false);
      }

      //检查版本更新
      if ($rootScope.config.isWebView == true) {
        $$AppUpdateService.checkVersion();
      }

      // 给安卓返回键注册一个事件
      $ionicPlatform.registerBackButtonAction(function(e) {
        e.preventDefault();
        // Is there a page to go back to?
        if ($location.path() == '/tab/home') {
          showisexitAppConfirm();
        } else if ($ionicHistory.backView()) {
          $ionicHistory.goBack();
        } else {
          // This is the last page: Show confirmation popup
          showisexitAppConfirm();
        }
        return false;
      }, 101);

      function showisexitAppConfirm() {
        var confirmPopup = $ionicPopup.confirm({
          title: '<strong>退出应用?</strong>',
          template: '你确定要退出应用吗?',
          okText: '退出',
          cancelText: '取消'
        });

        confirmPopup.then(function(res) {
          if (res) {
            ionic.Platform.exitApp();
          } else {
            // Don't close
          }
        });
      }

      if (Wechat != undefined) {
        // 检测 是否安装微信app
        Wechat.isInstalled(function(installed) {
          $rootScope.config.isInstallWeixinApp = true;
          $rootScope.config.isShowThreePartShare = true;
          $rootScope.config.isShowThreePartLogin = true;
          if ($rootScope.config.isIOS) {
            $rootScope.config.isShowThreePartShare = false;
            $rootScope.config.isShowThreePartLogin = false;
          }
        }, function(reason) {
          $rootScope.config.isInstallWeixinApp = false;
          $rootScope.config.isShowThreePartShare = false;
          $rootScope.config.isShowThreePartLogin = false;
        });
      }


    });


  })
  .filter('to_trusted', ['$sce', function($sce) {
    return function(text) {
      return $sce.trustAsHtml(text);
    };
  }])
  .filter('to_pricedouble', ['$sce', function($sce) {
    return function(text) {
      return text / 100;
    };
  }])
  .filter('to_dateYMDHM', ['$sce', function($sce) {
    return function(text) {
      if (text == undefined) {
        return "";
      }
      return text.substr(0, 16);
    };
  }])
  .filter('to_dateYMD', ['$sce', function($sce) {
    return function(text) {
      return text.substr(0, 10);
    };
  }]);
